package com.geralt.im.gui;

import java.awt.Color;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.JOptionPane;
import javax.swing.JTextField;

class TextFieldWithHint extends JTextField implements FocusListener {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private final String hint;
	private boolean showingHint;

	public TextFieldWithHint(final String hint) {
		super(hint);
		this.hint = hint;
		this.showingHint = true;
		super.addFocusListener(this);
	}
	public TextFieldWithHint(final String hint,String text) {
		super(text);
		this.hint = hint;
		this.showingHint = false;
		super.addFocusListener(this);
	}
	@Override
	public void focusGained(FocusEvent e) {
		if (this.getText().isEmpty()) {
			super.setText("");
			super.setForeground(Color.black);
			showingHint = false;
		}
	}

	@Override
	public void focusLost(FocusEvent e) {
		if (this.getText().isEmpty()) {
			super.setText(hint);
			super.setForeground(Color.gray);
			showingHint = true;
		}else if(this.getText().length()>20){
			JOptionPane.showMessageDialog(null, "username length cannont longer than 20!", "username oversize error", JOptionPane.ERROR_MESSAGE); 
		}
	}

	@Override
	public String getText() {
		return showingHint ? "" : super.getText();
	}
	@Override
	public void setText(String t){
		if(t!=null&&!"".equals(t)){
			this.showingHint = false;
		}
		super.setText(t);
		
	}
}
